# -*- coding: utf-8 -*-
# @Time : 2022/6/23 上午10:23
# @Author : wyf
# @FileName: login.py
# @Email: yunfei.wang@innvote.com
import time
from pprint import pprint

import execjs
import requests


def js_from_file(file_name):
    """
    读取js文件
    :return:
    """
    with open(file_name, 'r', encoding='UTF-8') as file:
        result = file.read()

    return result

# 编译加载js字符串
context = execjs.compile(js_from_file('./login.js'))

account = "124568665214@163.com"
password = "123456789"
res = context.call("data", account, password)   # 调用js方法
pprint(res)
headers = {
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Connection": "keep-alive",
    "Host": "login.10086.cn",
    "Referer": "https://login.10086.cn/html/login/email_login.html",
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-origin",
    "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1",
    "X-Requested-With": "XMLHttpRequest"
}


def login():
    session, code = get_session()

    _data = {
        "accountType": "02",
        "pwdType": "03",
        "account": res["account"],
        "password": res["password"],
        "inputCode": code,
        "backUrl": "https://touch.10086.cn/i/",
        "rememberMe": 0,
        "channelID": 12014,
        "protocol": "https:",
        "loginMode": "03",
        "timestamp": int(time.time() * 1000)
    }

    url = "https://login.10086.cn/login.htm"

    req = session.post(url=url, data=_data, headers=headers)
    print(req)
    pprint(req.json())


def get_session():
    cookies, session = get_cookie()
    text = get_code_text(open(f"./code_img/{cookies.get('rdmdmd5')}.png", "rb"))
    # print(cookies.get('rdmdmd5'), text)

    ss = session.get(f"https://login.10086.cn/verifyCaptcha?inputCode={text}", headers=headers)
    print(cookies.get('rdmdmd5'), text)
    if ss.status_code == 200 and ss.json().get("resultCode") == "0":
        print("验证码校验成功!!!")
        return session, text
    else:
        print("重新校验验证码中~~~")
        time.sleep(3)
        return get_session()


def get_cookie():
    """ 获取请求Cookie """
    session = requests.session()
    reqs = session.get("https://login.10086.cn/loadSendflag.htm?timestamp=", headers=headers)
    # print("get_send_flag", reqs.cookies)
    timestamp = str(int(time.time()*1000))
    _url = f"https://login.10086.cn/captchazh.htm?type=03&timestamp={timestamp}"
    coo = session.get(url=_url, headers=headers)
    # print(coo.content)
    with open(f"./code_img/{coo.cookies.get('rdmdmd5')}.png", "wb") as c:
        c.write(coo.content)
    # return f"CaptchaCode={coo.cookies.get('CaptchaCode')}; rdmdmd5={coo.cookies.get('rdmdmd5')}"
    return session.cookies, session


def get_code_text(image: bytes):
    """
    获取图片中的文字
    :param image:
    :return:
    """
    _url = 'http://192.168.1.211:8089/api/tr-run/'
    img1_file = {
        'file': image
    }
    data = {
        # 'compress': 0,  # 值为空时，默认将图片最长边压缩到1600px。 值为 0 时，不压缩图片。 值为非0 时，将最长边压缩到该值的大小
        'is_draw': 0  # 值为 0 时，不返回图片。（没有data['img_detected']返回）
    }
    _res = requests.post(url=_url, data=data, files=img1_file)
    try:
        # pprint(_res.json())
        for raw in _res.json().get("data")["raw_out"]:
            if raw[1]:
                return raw[1]
        return ""
    except Exception as e:
        print("获取图片中文字失败")
        return ""


if __name__ == '__main__':
    login()
